<template>
  <view class="content">
    <view class="ul">
      <view>姓名： {{userName}}</view>
    </view>
    
    <view class="btn-row">
      <button v-if="!hasLogin" type="primary" class="primary" @tap="bindLogin">登录</button>
      <button v-if="hasLogin" type="default" @tap="bindLogout">退出登录</button>
    </view>
  </view>
</template>

<script>
  import {
    mapState,
    mapMutations
  } from 'vuex'
  import service from '../../service.js'

  export default {
    data() {
      return {
        userName: ''
      }
    },
    onReady() {
      uni.request({
        url: service.getServer() + '/api/users/info',
        data: {},
        header: {
          'Authorization': service.getToken()
        },
        success: (res) => {
          if (res.statusCode !== 200) {
            uni.showToast({
              icon: 'none',
              title: '获取我的信息失败',
            });
          } else {
            this.userName = res.data.name
          }
        }
      })
    },
    computed: {
      ...mapState(['hasLogin', 'forcedLogin'])
    },
    methods: {
      ...mapMutations(['logout']),
      bindLogin() {
        uni.navigateTo({
          url: '../login/login',
        });
      },
      bindLogout() {
        this.logout();
        /**
         * 如果需要强制登录跳转回登录页面
         */
        if (this.forcedLogin) {
          uni.reLaunch({
            url: '../login/login',
          });
        }
      }
    }
  }
</script>

<style>

</style>
